import axios, {
    type AxiosInstance,
    type InternalAxiosRequestConfig, // 修改此处
    type AxiosResponse,
} from "axios";
import { message as antdMessage } from "ant-design-vue";
import {refreshToken} from "@/services/api/auth";
import {useOrgStore} from "@/store/modules/organization";

const API_URL = import.meta.env.VITE_API_BASE_URL;
// 创建 Axios 实例
const service: AxiosInstance = axios.create({
    baseURL: API_URL, // 设置基础 URL（从环境变量获取）
    timeout: 5000, // 请求超时时间
});
const token = localStorage.getItem("token") || sessionStorage.getItem("token");
let isRefreshing = false; // 标记是否正在刷新 token
let requestsQueue: Array<(token: string) => void> = []; // 存储等待刷新 token 后执行的请求

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 使用 InternalAxiosRequestConfig
        if (token) {
            config.headers!["Authorization"] = `Bearer ${token}`;
        }
        const orgStore = useOrgStore()
        config.headers!["Organization"] = orgStore.id;
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        return response.data;
    },
    async (error) => {
        antdMessage.error(error.response.data.message || error.message)
        const originalRequest = error.config as InternalAxiosRequestConfig & {
            _retry?: boolean;
        };
        // 检测是否是 token 过期错误
        if (
            error.response &&
            error.response.status === 401 &&
            !originalRequest._retry
        ) {
            originalRequest._retry = true;

            if (!isRefreshing) {
                isRefreshing = true;

                try {
                    // 调用刷新 token 接口
                    if (!token) {
                        return Promise.reject(new Error("没有找到token"))
                    }
                    const refreshResponse:ApiResponse<TokenResponse> = await refreshToken(token);

                    if (refreshResponse.code !== 200) {
                        return Promise.reject( Error(refreshResponse.message))
                    }
                    const newToken = refreshResponse.data.token;

                    // 更新 token
                    if (localStorage.getItem("token")) {
                        localStorage.setItem("token", newToken);
                    } else if (sessionStorage.getItem("token")) {
                        sessionStorage.setItem("token", newToken);
                    }

                    // 重新发送队列中的请求
                    requestsQueue.forEach((callback) => callback(newToken));
                    requestsQueue = [];
                    isRefreshing = false;

                    // 重新发起原始请求
                    originalRequest.headers["Authorization"] = `Bearer ${newToken}`;
                    return service(originalRequest);
                } catch (refreshError: any) {
                    antdMessage.error("登录已过期，请重新登录");
                    // 清除token
                    localStorage.removeItem("token");
                    sessionStorage.removeItem("token");
                    localStorage.removeItem("user");
                    isRefreshing = false;
                    window.location.href = "/#/login"; // 跳转到登录页
                    return Promise.reject(refreshError);
                }
            }

            // 将当前请求加入等待队列
            return new Promise((resolve) => {
                requestsQueue.push((token: string) => {
                    originalRequest.headers["Authorization"] = `Bearer ${token}`;
                    resolve(service(originalRequest));
                });
            });
        }

        return Promise.reject(error);
    }
);

// 将get/post/put/delete 封装入 request
export const request = {
    async get(url: string, params?: object): Promise<ApiResponse> {
        return await service.get(url, { params });
    },
    async post(url: string, data?: object, config?: object): Promise<ApiResponse> {
        return  await service.post(url, data, config);
    },
    async put(url: string, data?: object): Promise<ApiResponse> {
        return await service.put(url, data);
    },
    async del(url: string, params?: object): Promise<ApiResponse> {
        return  await service.delete(url, { params });
    }
};

// 导出默认方法
export default request;